﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LoadingUI : MonoBehaviour
{
    private string last;
    private string next;

    void Awake()
    {
        last = Engine.UISystem.last;
        next = Engine.UISystem.param as string;
    }
    
	void Start()
    {
        OnProgress(0);
        
        if (last.Equals("Login") || last.Equals("Name") || last.Equals("Game"))
        {
            StartCoroutine(LoadAsync("UI/", "Home"));
        }
        else if (last.Equals("Home"))
        {
            if (next.Equals("Start"))
            {
                StartCoroutine(LoadAsync("Prefab/Stage/", "Stage01"));
            }
            else if (next.Equals("Sound"))
            {
                StartCoroutine(LoadAsync("Prefab/Stage/", "Stage02"));
            }
            else if (next.Equals("Fly"))
            {
                StartCoroutine(LoadAsync("Prefab/Stage/", "Stage03"));
            }
            else if (next.Equals("Dream"))
            {
                StartCoroutine(LoadAsync("Prefab/Stage/", "Stage04"));
            }
        }
	}
	
	void Update()
    {
	
	}

    private IEnumerator LoadAsync(string path, string name)
    {
        int targerProgress = 0;
        int displayProgress = 0;

        ResourceRequest resourceRequest = Resources.LoadAsync(path + name);
        resourceRequest.allowSceneActivation = false;

        while (!resourceRequest.isDone)
        {
            targerProgress = (int)(resourceRequest.progress * 100);
            while (displayProgress < targerProgress)
            {
                this.OnProgress(++displayProgress);
                yield return null;
            }
            yield return null;
        }

        targerProgress = 100;
        while (displayProgress < targerProgress)
        {
            this.OnProgress(++displayProgress);
            yield return null;
        }

        this.OnComplete(name, resourceRequest.asset);

        resourceRequest.allowSceneActivation = true;
    }

    private void OnProgress(int progress)
    {
        transform.FindChild("TextRate").GetComponent<Text>().text = progress.ToString() + "%";
        transform.FindChild("SliderRate").GetComponent<Slider>().value = progress * 0.01f;
    }

    private void OnComplete(string name, Object asset)
    {
        if (name.Equals("Home"))
        {
            Engine.UISystem.Load(name, asset);
        }
        else if (name.Equals("Stage01") || name.Equals("Stage02") || name.Equals("Stage03") || name.Equals("Stage04"))
        {
            Engine.GameSystem.Load("System/InputSystem");
            Engine.GameSystem.Load(name, asset);

            //暂时未做设置当前场景为name
            Engine.UISystem.Load("Game");
        }
        
        Engine.UISystem.UnLoad("Loading");
    }
}
